﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace sqlDALgen.Renderers
{
    public class SplitRenderer : IRenderer
    {
        private readonly String _expr;
        private readonly String _on;
        private readonly String _cut;
        private int _start;
        private int _end;

        /// <summary>
        /// Checks if the loop where condition is matched
        /// accepts: data
        /// returns bool
        /// </summary>
        private readonly Func<TemplateData, bool> _wherePredicate;

        /// <summary>
        /// Checks if the loop counter is in range
        /// accepts: loop counter, data
        /// returns bool
        /// </summary>
        private readonly Func<int, TemplateData, bool> _rangePredicate;

        private readonly XmlNode _node;

        public static IRenderer Get(XmlNode node)
        {
            return new SplitRenderer(node);
        }

        public SplitRenderer(XmlNode node)
        {
            _node = node;
            _expr = node.Attributes["expr"].Value.ToString();
            _on = node.Attributes["on"].Value.ToString();
            _cut = node.Attributes["cut"] == null ? String.Empty : node.Attributes["cut"].Value.ToString();
        }

        public string FileName
        {
            get { throw new NotImplementedException(); }
        }

        public string Render(TemplateData data)
        {
            var builder = new StringBuilder();
            var sourceData = data;

            var splitVal = TemplateRenderer.FillData(_expr, data).Split('.');

            data = new TemplateData { 
                            { "item", new TemplateData() },
                            { "ctx", sourceData }
                        };

            var cnt = 0;
            foreach (var s in splitVal)
            {
                data["item"].Add(cnt.ToString(), TemplateData.ValueNode(s));
                cnt++;
            }

            foreach (XmlNode node in _node.ChildNodes)
            {
                builder.Append(TemplateRenderer.Get(node).Render(data));
            }

            if (String.IsNullOrEmpty(_cut))
                return builder.ToString();
            else
                return builder.Remove(builder.Length + Int32.Parse(_cut), Math.Abs(Int32.Parse(_cut))).ToString();
        }
    }
}
